/*
 * File: Credits.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import data.SignedRequest;
import faceBook.Purchase;
import faceBook.User;

import java.sql.Timestamp;
import java.util.GregorianCalendar;
import java.util.logging.Logger;

/**
 * The Class javaScriptServlet.
 * 
 * @author Dude
 */
public class Credits extends FoxtrotBravoServlet
{

  private static final Logger log = Logger.getLogger(Credits.class.getName());

  /*
   * (non-Javadoc)
   * 
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    for (Object key : req.getParameterMap().keySet())
    {
      log.info(key + "=" + req.getParameter((String) key));
    }
    if (req.getParameter("signed_request") != null)
    {
      log.info(SignedRequest.parseAfterDot(req.getParameter("signed_request"))
          .toString());
    }
    try
    {
      if ("payments_get_items".equals(req.getParameter("method")))
      {
        if (req.getParameter("order_info") != null)
        {
          resp.getWriter().write(
              postItemData(new JSONObject(req.getParameter("order_info"))));
        }
      } else if ("payments_status_update".equals(req.getParameter("method")))
      {
        if (req.getParameter("order_details") != null
            && req.getParameter("status") != null)
        {
          resp.getWriter().write(
              storePurchase(new JSONObject(req.getParameter("order_details")),
                  req.getParameter("status")));
        }
      }
    } catch (JSONException e)
    {
      e.printStackTrace();
    }
  }

  /**
   * Post item data.
   * 
   * @param orderInfo
   *          the order info
   * @return the string
   * @throws JSONException
   *           the jSON exception
   */
  private static String postItemData(JSONObject orderInfo) throws JSONException
  {
    int customMessages = orderInfo.getInt("customMessages");
    int price;
    if (customMessages == 100)
    {
      price = 10;
    } else if (customMessages == 600)
    {
      price = 50;
    } else
    {
      return "";
    }
    JSONObject retVal = new JSONObject();
    JSONArray content = new JSONArray();
    JSONObject data = new JSONObject();
    data.put("title", "Additional Custom Messages");
    data.put("description", String.valueOf(customMessages) + " Custom Messages");
    data.put("image_url",
        "http://foxtrotbravodehack3.appspot.com/img/logo-75.png");
    data.put("product_url", "http://foxtrotbravodehack3.appspot.com/");
    data.put("price", price);
    content.put(data);
    retVal.put("content", content);
    retVal.put("method", "payments_get_items");
    return retVal.toString(4);
  }

  /**
   * Handle purchase info.
   * 
   * @param orderDetails
   *          the order details
   * @return the string
   * @throws JSONException
   *           the jSON exception
   */
  private static String storePurchase(JSONObject orderDetails, String status)
      throws JSONException
  {
    int price = orderDetails.getInt("amount");
    long orderId = orderDetails.getLong("order_id");
    User user = new User(orderDetails.getLong("buyer"));
    int customMessages;
    if (price == 10)
    {
      customMessages = 100;
    } else if (price == 50)
    {
      customMessages = 600;
    } else
    {
      return "";
    }
    if ("placed".equals(status))
    {
      Purchase purchase = new Purchase();
      purchase.setMessageCount(customMessages);
      purchase.setOrderId(orderId);
      purchase.setPrice(price);
      purchase
          .setTime(new Timestamp(new GregorianCalendar().getTimeInMillis()));
      purchase.setUser(user);
      if (!purchase.save())
        return "";
    }
    JSONObject retVal = new JSONObject();
    JSONObject content = new JSONObject();
    content.put("status", "settled");
    content.put("order_id", orderId);
    retVal.put("content", content);
    retVal.put("method", "payments_status_update");
    return retVal.toString(4);
  }
}
